package comm

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"log4go"
	"net"
	"strings"
	"tool"
)

func ServerBuild(opt, url string) {
	listener, err := net.Listen(opt, url)
	if err != nil {
		fmt.Println("listen error:", err.Error())
		return
	}

	defer listener.Close()

	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("accept error:", err.Error())
			return
		}

		go ReadConn(conn)
	}
}

func ReadConn(conn net.Conn) {
	remoteAddr := conn.RemoteAddr()
	log4go.Debug("connect addr : %s", remoteAddr)

	defer conn.Close()

	for {
		buf := make([]byte, 1024)
		length, err := conn.Read(buf)
		if err != nil {
			if strings.EqualFold(err.Error(), "EOF") == true {
				log4go.Debug("client close link")
				return
			}
			log4go.Debug("read error: %s", err.Error())
			return
		}

		b_buf := bytes.NewBuffer(buf)
		var mlen int32
		binary.Read(b_buf, binary.BigEndian, &mlen)

		head := string(buf[4 : mlen+4])
		body := string(buf[mlen+6 : length])

		log4go.Debug("body[%s].head[%s].leng[%d][%d]", body, head, length, mlen)

		str_hjson, str_bjson, err := AnalyMsg(head, body[:int32(length)-mlen-6])

		mlen = (int32)(len(str_hjson))
		str_msg := tool.Byte2String(str_hjson) + "\r\n" + tool.Byte2String(str_bjson)

		b_buf = bytes.NewBuffer([]byte{})
		binary.Write(b_buf, binary.BigEndian, mlen)

		b_buf.WriteString(str_msg)

		conn.Write([]byte(b_buf.String()))

	}
}
